package com.example.wsServer;

import com.alibaba.fastjson.JSONObject;
import com.example.netty.ChatCode;
import com.example.netty.nettyUserInfo;
import com.example.netty.nettyUserManager;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

/**
 * @author Andy
 * @site http://www.wolfbe.com
 * @github https://github.com/beyondfengyu
 */
@Slf4j
public class MessageHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame frame)
            throws Exception {
        nettyUserInfo userInfo = nettyUserManager.getUserInfo(ctx.channel());

        log.info(userInfo.toString()+"------------------------------------------");
        if (userInfo != null && userInfo.isAuth()) {
            JSONObject json = JSONObject.parseObject(frame.text());
            // 广播返回用户发送的消息文本    // UID // 昵称
            log.info(userInfo.toString()+"11111111111111111111111111111111");

            nettyUserManager.broadcastMess(userInfo.getUserId(), userInfo.getNick(), json.getString("mess"));
        }
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        nettyUserManager.removeChannel(ctx.channel());
        //更新统计在线人数
        nettyUserManager.broadCastInfo(ChatCode.SYS_USER_COUNT,nettyUserManager.getAuthUserCount());
        super.channelUnregistered(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("connection error and close the channel", cause);
        nettyUserManager.removeChannel(ctx.channel());
        nettyUserManager.broadCastInfo(ChatCode.SYS_USER_COUNT, nettyUserManager.getAuthUserCount());
    }

}
